package sys_user

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"gvb_server/global"
	system "gvb_server/models/system/dto"
	login "gvb_server/models/system/req"
	response "gvb_server/models/system/resp"
	"gvb_server/models/system/resp/code"
	jwt "gvb_server/utils/jwt"
	verify "gvb_server/utils/validator"
)

// Login
// @Tags     Base
// @Summary  用户登录
// @Produce   application/json
// @Param    data  body      systemReq.Login                                             true  "用户名, 密码, 验证码"
// @Success  200   {object}  response.Response{data=systemRes.LoginResponse,msg=string}  "返回包括用户信息,token,过期时间"
// @Router   /base/login [post]
func (b *SysUserApi) Login(c *gin.Context) {
	var l login.Login
	err := c.ShouldBindBodyWith(&l, binding.JSON)
	if err != nil {
		code.ErrorWithError(c, code.RequestParamError, err)
		return
	}
	err = verify.Verify(l, verify.LoginVerify)
	if err != nil {
		code.ErrorWithError(c, code.RequestParamError, err)
		return
	}

	u := &system.SysUser{Username: l.Username, Password: l.Password}
	user, err := userService.Login(u)
	if err != nil {
		code.ErrorWithMsg(c, code.UsernameOrPasswordError, "用户名不存在或者密码错误")
		return
	}
	if user.Enable != 1 {
		code.ErrorWithMsg(c, code.UserForbidden, "用户被禁止登录")
		return
	}
	b.TokenNext(c, *user)
	return

}

// TokenNext 登录以后签发jwt
func (b *SysUserApi) TokenNext(c *gin.Context, user system.SysUser) {
	j := &jwt.JWT{SigningKey: []byte(global.Config.JWT.SigningKey)} // 唯一签名
	claims := j.CreateClaims(jwt.BaseClaims{
		UUID:     user.Id,
		Username: user.Username,
	})
	token, err := j.CreateToken(claims)
	if err != nil {
		code.ErrorWithMsg(c, code.GenerateTokenError, "获取token失败")
		return
	}
	c.SetCookie("token", token, 3600, "", "", false, true)
	code.OKWithData(c, response.LoginResponse{
		User:      user,
		Token:     token,
		ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
	})
	return

}
